package com.baozun.houji.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import com.ashokvarma.bottomnavigation.BottomNavigationItem
import com.ashokvarma.bottomnavigation.TextBadgeItem
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseActivity
import com.baozhun.mall.common.base.BaseApplication
import com.baozhun.mall.common.ext.checkLogin
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.enums.MainNavigateType
import com.baozhun.mall.common.util.CacheUtil
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.util.eventbus.EventMessage
import com.baozhun.mall.common.util.onkeylogin.OneKeyLoginHelper
import com.baozun.houji.R
import com.baozun.houji.adapter.MainNavigateAdapter
import com.baozun.houji.databinding.ActivityMainBinding
import com.baozun.houji.goods.fragment.HomeFragment
import com.baozun.houji.me.fragment.MeFragment
import com.baozun.houji.me.fragment.MessageFragment
import com.baozun.houji.viewmodel.MainViewModel
import com.jaeger.library.StatusBarUtil
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Title：项目主页Activity
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2022/11/4
 * @Version：1.0.0
 */
@Route(path = RoutePath.Main.MAIN)
class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>(), BottomNavigationBar.OnTabSelectedListener {

    private var mExitTime: Long = 0
    private var mAlrShowContinueBuyTipDialog: Boolean = false //是否已经显示过连单提示dialog
    private var mFragmentList = arrayListOf<Fragment>()
    private lateinit var homeFragment: HomeFragment
    private lateinit var brandFragment: MessageFragment
    private lateinit var continueBuyFragment: MessageFragment
    private lateinit var messageFragment: MessageFragment
    private lateinit var meFragment: MeFragment
    private lateinit var numberBadgeItem: TextBadgeItem

    companion object {
        fun start(context: Context) {
            var intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getMsgCount()
    }

    override fun initView(savedInstanceState: Bundle?) {
        OneKeyLoginHelper.getInstance().initOneKeyLogin(this)
        initFragment()
        EventBusUtils.register(this)
        StatusBarUtil.setColor(this, getColor(com.baozhun.mall.res.R.color.trans_parent))
        StatusBarUtil.setTranslucentForImageViewInFragment(this@MainActivity, 0, null)
        //初始化viewpager2
        mDataBinding.mainViewpager.isUserInputEnabled = false
        mDataBinding.mainViewpager.offscreenPageLimit = mFragmentList.size
        mDataBinding.mainViewpager.adapter = MainNavigateAdapter(this, mFragmentList)

        numberBadgeItem = TextBadgeItem().setBackgroundColorResource(com.baozhun.mall.res.R.color.color_FC0503).hide()
        mDataBinding. bottomNavigationBar.setTabSelectedListener(this)
        mDataBinding.bottomNavigationBar.addItem(BottomNavigationItem(com.baozhun.mall.common.R.drawable.ic_tab_home_press, com.baozhun.mall.res.R.string.main_tab_home).setInactiveIconResource(com.baozhun.mall.common.R.drawable.ic_tab_home).setActiveColorResource(com.baozhun.mall.res.R.color.color_666))
        mDataBinding.bottomNavigationBar.addItem(BottomNavigationItem(com.baozhun.mall.common.R.drawable.ic_tab_brand_press, com.baozhun.mall.res.R.string.main_tab_brand).setInactiveIconResource(com.baozhun.mall.common.R.drawable.ic_tab_brand).setActiveColorResource(com.baozhun.mall.res.R.color.color_666))
        mDataBinding.bottomNavigationBar.addItem(BottomNavigationItem(com.baozhun.mall.common.R.drawable.ic_tab_brand_press, com.baozhun.mall.res.R.string.message, ).setInactiveIconResource(com.baozhun.mall.common.R.drawable.ic_tab_brand_press).setActiveColorResource(com.baozhun.mall.res.R.color.color_666))
        mDataBinding.bottomNavigationBar.addItem(BottomNavigationItem(com.baozhun.mall.common.R.drawable.ic_tab_message_press, com.baozhun.mall.res.R.string.message).setInactiveIconResource(com.baozhun.mall.common.R.drawable.ic_tab_message).setActiveColorResource(com.baozhun.mall.res.R.color.color_666).setBadgeItem(numberBadgeItem))
        mDataBinding.bottomNavigationBar.addItem(BottomNavigationItem(com.baozhun.mall.common.R.drawable.ic_tab_me_press, com.baozhun.mall.res.R.string.main_tab_me).setInactiveIconResource(com.baozhun.mall.common.R.drawable.ic_tab_me).setActiveColorResource(com.baozhun.mall.res.R.color.color_666)).initialise()
    }

    override fun initData() {
        super.initData()
    }

    /**
     * 初始化fragment
     */
    private fun initFragment() {
        homeFragment = HomeFragment()
        brandFragment = MessageFragment()
        continueBuyFragment = MessageFragment()
        messageFragment = MessageFragment()
        meFragment = MeFragment()

        mFragmentList.add(homeFragment)
        mFragmentList.add(brandFragment)
        mFragmentList.add(continueBuyFragment)
        mFragmentList.add(messageFragment)
        mFragmentList.add(meFragment)
    }

    override fun createObserver() {
        BaseApplication.mEventViewModelInstance.switchTabEvent.observeInActivity(this, Observer {
            performTabClick(it)
        })
        mViewModel.mMsgCount.observe(this) {
            if (it != null && it > 0) {
                numberBadgeItem.setText(it.toString())
                numberBadgeItem.show()
            }

        }
        mViewModel.mClearMsgSuccess.observe(this) {
            numberBadgeItem.hide()
        }
    }

    private fun performTabClick(navigateType: Int) {
        when (navigateType) {
            MainNavigateType.HOME.ordinal -> mDataBinding.bottomNavigationBar.selectTab(mFragmentList.indexOf(homeFragment))
            MainNavigateType.BRAND.ordinal -> checkLogin { mDataBinding.bottomNavigationBar.selectTab(mFragmentList.indexOf(brandFragment)) }
            MainNavigateType.ORDER.ordinal -> checkLogin {
                mDataBinding.bottomNavigationBar.selectTab(mFragmentList.indexOf(continueBuyFragment))
            }

            MainNavigateType.MESSAGE.ordinal -> checkLogin {
                mViewModel.readMsg()
                mDataBinding.bottomNavigationBar.selectTab(mFragmentList.indexOf(messageFragment))
            }

            MainNavigateType.ME.ordinal -> checkLogin { mDataBinding.bottomNavigationBar.selectTab(mFragmentList.indexOf(meFragment)) }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage<Any>) {
        if (event.eventCode == EventCode.LOGIN_SUCCESS) {
            OneKeyLoginHelper.getInstance().closeLoginPage()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mExitTime > Constants.Common.EXIT_APP_TIME) {
                showToast(com.baozhun.mall.res.R.string.exit_hint)
                mExitTime = System.currentTimeMillis()
            } else {
                BaseApplication.mInstance.exitApp()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onTabSelected(position: Int): Boolean {
        var notNeedLoginList = getNotNeedLoginTabPosition()
        if (notNeedLoginList.contains(position)) {
            mDataBinding.mainViewpager.setCurrentItem(position, false)
        } else {
            checkLogin {
                mDataBinding.mainViewpager.setCurrentItem(position, false)
            }
        }
        //处理消息已读逻辑
        handelMsgRead(position)
        return CacheUtil.isLogin() || notNeedLoginList.contains(position)
    }

    /**
     * 处理消息已读状态
     */
    private fun handelMsgRead(position: Int) {
        if (mFragmentList.indexOf(messageFragment) == position) {
            mViewModel.readMsg()
        }
    }


    override fun onTabUnselected(position: Int) {
    }

    override fun onTabReselected(position: Int) {
    }

    /**
     * 获取不需要登录的额tab位置
     */
    private fun getNotNeedLoginTabPosition(): ArrayList<Int> {
        return arrayListOf(MainNavigateType.HOME.ordinal, MainNavigateType.BRAND.ordinal)
    }
}
